﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Markup;
using System.IO;
using System.Runtime.Serialization;

namespace SMS.Common.Runtime
{
    public class XmlFormater
    {
        public static string SerializeObject(object obj)
        {
            
            NetDataContractSerializer ndcs = new NetDataContractSerializer();
            return Serialize(obj, ndcs);
        }
        public static string SerializeDataContract(object obj)
        {
            return SerializeDataContract(obj, null);
        }
        public static string SerializeDataContract(object obj, IEnumerable<Type> knownTypes)
        {
            DataContractSerializer dcs = new DataContractSerializer(obj.GetType(), knownTypes);
            return Serialize(obj, dcs);
        }
        private static string Serialize(object obj, XmlObjectSerializer serializer)
        {
            StringBuilder sb = new StringBuilder();
            XmlWriter xw = XmlWriter.Create(sb);
            serializer.WriteObject(xw, obj);
            xw.Close();
            return sb.ToString();
        }
        public static T DeserializeObject<T>(string xml)
        {
            NetDataContractSerializer ndcs = new NetDataContractSerializer();
            return (T)Deserialize(xml, ndcs);
        }
        public static T DeserializeDataContract<T>(string xml)
        {
            return (T)DeserializeDataContract(xml, typeof(T), null);
        }
        public static T DeserializeDataContract<T>(string xml, IEnumerable<Type> knownTypes)
        {
            return (T)DeserializeDataContract(xml, typeof(T), knownTypes);
        }
        public static object DeserializeDataContract(string xml, Type type, IEnumerable<Type> knownTypes)
        {
            DataContractSerializer dcs = new DataContractSerializer(type, knownTypes);
            return Deserialize(xml, dcs);
        }
        private static object Deserialize(string xml, XmlObjectSerializer serializer)
        {
            StringReader sr = new StringReader(xml);
            XmlReader xr = XmlReader.Create(sr);

            object obj = serializer.ReadObject(xr);
            return obj;
        }
        public static string SerializeToXaml(object obj)
        {
            return XamlWriter.Save(obj);

        }
        public static T DeserializeFromXaml<T>(string xml)
        {
            StringReader stringReader = new StringReader(xml);
            XmlReader xmlReader = XmlReader.Create(stringReader);
            return (T)XamlReader.Load(xmlReader);


        }


    }
}
